package com.meixiang.activity.moments;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.adapter.moments.CommunityNewsAdapter;
import com.meixiang.entity.account.CommunityNewsList;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 作者：黑哥 on 2016/5/7 11:58
 * <p/>
 * 社区消息
 */
public class CommunityNewsActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener
{

    @Bind(R.id.swipe_target)
    RecyclerView mRecyclerView;
    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;
    private CommunityNewsAdapter mAdapter;
    private Activity mActivity;

    private int mPageNo = 1, pageSize = 10, totalPage = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_community_news);
        ButterKnife.bind(this);
        mActivity=CommunityNewsActivity.this;
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initTitle() {
        setRightTitle("社区消息", "清空", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                HttpUtils.post(Config.ACCOUNT_DELETE_MESSAGE, null, new HttpCallBack(mActivity) {
                    @Override
                    public void onSucceed(JSONObject result, String code, String message) {
                        Tool.showTextToast(mActivity,result.optString("message"));
                        //调用刷新
                        onRefresh();
                    }

                    @Override
                    public void onError(String code, String message) {
                        Tool.showTextToast(mActivity,message);
                    }
                });
            }

        });
    }

    @Override
    protected void initView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mAdapter = new CommunityNewsAdapter(mActivity);
        mRecyclerView.setAdapter(mAdapter);

        mRefresh.setOnRefreshListener(this);
        mRefresh.setOnLoadMoreListener(this);

        /**检查RecyclerView是否滑动底部如果滑到*/
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (!ViewCompat.canScrollVertically(recyclerView, 1)) {
                        mRefresh.setLoadingMore(true);
                    }
                }
            }
        });

        mAdapter.setOnItemClickListener(new CommunityNewsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent=new Intent(mActivity, PostDetailsActivity.class);
                intent.putExtra("commentId",mAdapter.getData().get(position).getCommentId());
                startActivity(intent);

            }
        });
    }

    @Override
    protected void setData() {
        status.showLoading();
        getAttentionData(true);
    }
    private void getAttentionData( final boolean isPull){
        HttpParams params = new HttpParams();
        params.put("pageSize", pageSize + "");
        params.put("pageNo", mPageNo + "");
        HttpUtils.post(Config.ACCOUNT_MESSAGE_COMMUNITY, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                if (isPull){
                    mAdapter.clearData();
                }
                mPageNo=result.optInt("pageNo");
                totalPage=result.optInt("totalPage");
                List<CommunityNewsList> mList= AbJsonUtil.fromJson(result.optJSONArray("messageList").toString(),new TypeToken<List<CommunityNewsList>>(){});
                if (mList!=null&&mList.size()>0){
                    status.removeView();
                    mAdapter.addAll(mList);
                }else{
                    status.showNoData("暂无数据");
                }
            }

            @Override
            public void onError(String code, String message) {
                status.showNoNewWork(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getAttentionData(isPull);
                    }
                });

                if (message.equals("暂无数据")){
                    status.showNoData("暂无数据");
                }else{
                    status.showNoData(message, "重新加载", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            status.showLoading();
                            getAttentionData(isPull);
                        }
                    });
                }
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                if (mRefresh.isRefreshing()){
                    mRefresh.setRefreshing(false);
                }else{
                    mRefresh.setLoadingMore(false);
                }
            }
        });
    }
    @Override
    public void onClick(View v) {

    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        if (mPageNo<totalPage){
            mPageNo++;
            getAttentionData(false);
        }else{
            AbToastUtil.showToast(activity,"已无更多数据");
            mRefresh.setLoadingMore(false);
        }
    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        mPageNo = 1;
        getAttentionData(true);
    }

}
